package de.hm.edu.c2dm;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

/** 
 * A helper class to handle C2DM messaging
 * 
 * @author Peter Goldenbogen (Munich University of Applied Science)
 * @version 1.0 
 */
public class MessageUtil {

	/**C2DM URL Param*/
	public static final String PARAM_REGISTRATION_ID = "registration_id";
	/**C2DM URL Param*/
	public static final String PARAM_COLLAPSE_KEY = "collapse_key";
	/**Post data encoding */
	private static final String UTF8 = "UTF-8";

	/**
	 * Sends a C2DM Message to all recipients stored in the DB
	 * @param message The message content
	 */
	public static void c2dmPush(String message){
		
		C2dmRecipientsContainer container = new C2dmRecipientsContainer();
		
		for(String registrationId : container.getRecipients()){
			try {
				sendMessage(registrationId, message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * sends a message to one single C2DM Recipient
	 * @param registrationId C2DM Token to identify the recipient
	 * @param message The message content
	 * @return HTTP Response code received b C2DM Server
	 * @throws IOException
	 */
	private static int sendMessage(String registrationId, String message) throws IOException {

		StringBuilder postDataBuilder = new StringBuilder();
		postDataBuilder.append(PARAM_REGISTRATION_ID).append("=").append(registrationId);
		postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=").append("0");
		postDataBuilder.append("&").append("data.payload").append("=").append(URLEncoder.encode(message, UTF8));

		byte[] postData = postDataBuilder.toString().getBytes(UTF8);

		// connect to C2DM URL
		URL url = new URL("https://android.clients.google.com/c2dm/send");
		HttpsURLConnection.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
		conn.setRequestProperty("Content-Length",Integer.toString(postData.length));
		conn.setRequestProperty("Authorization", "GoogleLogin auth="+ AuthenticationUtil.getAuth_token());

		OutputStream out = conn.getOutputStream();
		out.write(postData);
		out.close();

		int responseCode = conn.getResponseCode();
		return responseCode;
	}

	private static class CustomizedHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}
}
